package com.github.shiqiyue.app.config.webmvc;


import com.github.shiqiyue.app.common.trace.TraceConstants;
import com.github.shiqiyue.app.common.trace.TraceIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/***
 * traceId生成过滤器
 * @author wenyao.wu
 * @date 2019/10/26
 */
@Slf4j
public class TraceIdGenerateFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        try {
            MDC.put(TraceConstants.TRACE_ID, TraceIdGenerator.generate());
        } catch (Exception e) {
            log.error("设置traceId失败", e);
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
        try {
            MDC.remove(TraceConstants.TRACE_ID);
        } catch (Exception e) {
            log.error("删除traceId失败", e);
        }

    }
}
